package com.translate.web.api.controller;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.aliyun.oss.ClientException;
import com.common.util.GenerateRandomCode;
import com.translate.web.annotation.JwtIgnore;
import com.response.vo.ResponseModel;
import com.sms.aliyun.SendMessageUtil;
import com.sms.aliyun.SmsRequestParam;
import com.sms.aliyun.msg.Message;
import com.translate.web.config.SmsRequestConfig;
import com.translate.web.constant.RedisConstant;
import com.translate.web.param.SendPhoneNumber;



@RestController
@RequestMapping("/api/sms")
public class SendSmsController {

	private SmsRequestConfig smsRequestConfig;
	
	private RedisTemplate<String, String> redisTemplate;
	
	
	public SendSmsController(SmsRequestConfig smsRequestConfig) {
		this.smsRequestConfig = smsRequestConfig;
	}

	@PostMapping("/getCode")
	@JwtIgnore
	public ResponseModel<Integer> getCode(@RequestBody @Validated SendPhoneNumber sendPhoneNumber) throws ClientException, InterruptedException, ExecutionException {
		
		String code = GenerateRandomCode.getSixNum();
		
		String phone = sendPhoneNumber.getPhone();
		
		Message message = new Message(phone, smsRequestConfig.getSignName(), smsRequestConfig.getTemplateCode(), "{code:" + code + "}");
		
		SmsRequestParam smsRequestParam = new SmsRequestParam();
		
		smsRequestParam.setAccessKeyId(smsRequestConfig.getAccessKeyId());
		
		smsRequestParam.setAccessKeySecret(smsRequestConfig.getAccessKeySecret());
		
		smsRequestParam.setDomain(smsRequestConfig.getDomain());
		
		smsRequestParam.setRegionId(smsRequestConfig.getRegionId());
		
		if (!SendMessageUtil.sendSms(message, smsRequestParam)) {
			return ResponseModel.<Integer>errorMsg(0, "发送失败");
		}
		
		ValueOperations<String, String> valueOperations = this.redisTemplate.opsForValue();
		
		valueOperations.set(RedisConstant.getSmsByKey(phone), code, 5, TimeUnit.MINUTES);
		
		return ResponseModel.<Integer>success(1);
	}

	@Autowired
	public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
}
